from django.contrib import messages
from django.utils.translation import gettext as _, gettext_lazy
from datetime import datetime
from django.urls import NoReverseMatch, reverse
from django.http import HttpResponseRedirect


def _with_improt_wechat(username, nickname):
    def to_selected(modeladmin, request, queryset):
        from manualpick.models import TMobilePick

        n = 0
        success = 0
        objs = TMobilePick.objects
        n = n + 1
        for obj in queryset:
            pick_obj, created = objs.get_or_create(
                mobile=obj.mobile,
                defaults={'wechat': username,
                          'note': nickname,
                          'create_user': request.user,
                          'client_ip': request.META['REMOTE_ADDR'],
                          'status': 0,
                          'status_text': "from %s at %s" % (
                              obj.create_user, datetime.now())
                          })
            success = success + (1 if created else 0)

        queryset.update(status=1, status_text="to:%s" % username)

        modeladmin.message_user(request, _("Successfully select %(count)d, %(succed) succed") % {
            "count": n, "succed": success}, messages.SUCCESS)

        info = queryset.model._meta.app_label, queryset.model._meta.model_name
        name = 'admin:%s_%s_changelist' % info
        index_path = reverse(name)

        return HttpResponseRedirect(index_path)

    action = to_selected
    action.short_description = "提取 微信号: %s" % nickname
    action.__name__ = "to:%s" % username

    return action
